import React, { useEffect, useState, useReducer, useMemo } from 'react';
import clsx from 'clsx';
import { Text, View, router, Picker, showToast, device, getLaunchOptionsSync, onDeviceInfoUpdated } from '@ray-js/ray';
import MinusCircle from '@tuya-miniapp/icons/dist/svg/MinusCircle';
import PlusCircle from '@tuya-miniapp/icons/dist/svg/PlusCircle';
import Right from '@tuya-miniapp/icons/dist/svg/Right';
import { useActions, useProps } from '@ray-js/panel-sdk';
import { NavBar, Battery, Icon, Dialog, Field } from '@ray-js/smart-ui';
import Strings from '@/i18n';
import debounce from 'lodash/debounce';

import SmartSwitch from '@/components/SmartSwitch';

import * as Raw from '@/utils/raw';
import styles from './index.module.less';

type State = {
  timerSwitch: boolean;
  timerHour: number;
  startHour: number;
  startMinute: number;
  endHour: number;
  endMinute: number;
  gear: number;
  scene: number;
};

type Action<K extends keyof State = keyof State> = {
  type: 'SET';
  key: K;
  value: State[K];
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET':
      return {
        ...state,
        [action.key]: action.value,
      };

    default:
      return state;
  }
}

const initialState: State = {
  timerSwitch: false,
  timerHour: 0,
  startHour: 0,
  startMinute: 0,
  endHour: 0,
  endMinute: 0,
  gear: 1,
  scene: 0,
};

const days = [
  Strings.getLang('sun'),
  Strings.getLang('mon'),
  Strings.getLang('tue'),
  Strings.getLang('wed'),
  Strings.getLang('thu'),
  Strings.getLang('fri'),
  Strings.getLang('sat'),
];

const SCENE_LLIST = [
  {
    key: 1,
    label: Strings.getLang('livingRoom'),
    icon: require('@/res/icons/scene1.svg'),
    checkIcon: require('@/res/icons/scene1_white.svg'),
  },
  {
    key: 2,
    label: Strings.getLang('bedroom'),
    icon: require('@/res/icons/scene2.svg'),
    checkIcon: require('@/res/icons/scene2_white.svg'),
  },
  {
    key: 3,
    label: Strings.getLang('studyRoom'),
    icon: require('@/res/icons/scene3.svg'),
    checkIcon: require('@/res/icons/scene3_white.svg'),
  },
  {
    key: 4,
    label: Strings.getLang('dressingRoom'),
    icon: require('@/res/icons/scene4.svg'),
    checkIcon: require('@/res/icons/scene4_white.svg'),
  },
  {
    key: 5,
    label: Strings.getLang('bathroom'),
    icon: require('@/res/icons/scene5.svg'),
    checkIcon: require('@/res/icons/scene5_white.svg'),
  },
  {
    key: 6,
    label: Strings.getLang('childrenRoom'),
    icon: require('@/res/icons/scene6.svg'),
    checkIcon: require('@/res/icons/scene6_white.svg'),
  },
  {
    key: 7,
    label: Strings.getLang('hall'),
    icon: require('@/res/icons/scene7.svg'),
    checkIcon: require('@/res/icons/scene7_white.svg'),
  },
  {
    key: 8,
    label: Strings.getLang('office'),
    icon: require('@/res/icons/scene8.svg'),
    checkIcon: require('@/res/icons/scene8_white.svg'),
  },
  {
    key: 9,
    label: Strings.getLang('diningRoom'),
    icon: require('@/res/icons/scene9.svg'),
    checkIcon: require('@/res/icons/scene9_white.svg'),
  },
  {
    key: 10,
    label: Strings.getLang('cafe'),
    icon: require('@/res/icons/scene10.svg'),
    checkIcon: require('@/res/icons/scene10_white.svg'),
  },
  {
    key: 11,
    label: Strings.getLang('yogaStudio'),
    icon: require('@/res/icons/scene11.svg'),
    checkIcon: require('@/res/icons/scene11_white.svg'),
  },
];

const isWifiDevice = false;

export default function Home() {
  const { getDeviceInfo, registerDeviceListListener, onDeviceOnlineStatusUpdate } = device;
  const [state, dispatch] = useReducer(reducer, initialState);
  const power = useProps(props => props.switch); // 开关
  const battery = useProps(props => props.battery_percentage); // 电量
  const scene = useProps(props => props.scene); // 场景
  const timer = useProps(props => props.timer); // 定时
  const timerCountDown = useProps(props => props.timer_count_down); // 定时剩余时间
  const aromaName = useProps(props => props.aroma_name); // 精油名称
  const work = useProps(props => props.work); // 工作状态


  const actions = useActions();

  const [sceneList, setSceneList] = useState([1, 2, 0, 0]);
  const [sceneIndex, setSceneIndex] = useState(0);

  const [deviceInfo, setDeviceInfo] = useState<any>({});
  const [selectedDays, setSelectedDays] = useState<number[]>([]);
  const [aromaNameField, setAromaNameField] = useState<string>('');
  const [showAromaNameDialog, setShowAromaNameDialog] = useState(false);

  // 处理精油名称确认
  const handleAromaNameConfirm = () => {
    if (aromaNameField.trim() === '') {
      showToast({ title: Strings.getLang('toast1') });
      return;
    }
    setShowAromaNameDialog(false);
    actions.aroma_name.set(aromaNameField);
    showToast({ title: Strings.getLang('toast2') });
    setAromaNameField('');
  };

  useEffect(() => {
    const {
      query: { deviceId },
    } = getLaunchOptionsSync();

    getDeviceInfo({
      deviceId,
      success: info => {
        console.log('getDeviceInfo success', info);
        setDeviceInfo(info);
      },
    });
    registerDeviceListListener({ deviceIdList: [deviceId] });
    onDeviceOnlineStatusUpdate(env => {
      getDeviceInfo({
        deviceId,
        success: info => {
          console.log('getDeviceInfo success', info);
          setDeviceInfo(info);
        },
      });
    });

    onDeviceInfoUpdated(_ => {
      getDeviceInfo({
        deviceId,
        success: info => {
          setDeviceInfo(info);
        },
      });
    });
  }, []);

  useEffect(() => {
    if (scene) {
      const { currentScene, scene1, scene2, scene3, scene4 } = Raw.parseSceneRaw(scene);
      setSceneIndex([scene1, scene2, scene3, scene4].indexOf(currentScene));
      dispatch({ type: 'SET', key: 'scene', value: currentScene });
      setSceneList([scene1, scene2, scene3, scene4]);
    }
    if (timer) {
      const { isOn, hour } = Raw.parseTimingRaw(String(timer).trim());
      dispatch({ type: 'SET', key: 'timerSwitch', value: isOn });
      dispatch({ type: 'SET', key: 'timerHour', value: hour - 1 });
    }
    if (work) {
      const { gear, startHour, startMinute, endHour, endMinute, days } = Raw.parseWorkRaw(work);
      dispatch({ type: 'SET', key: 'gear', value: gear });
      dispatch({ type: 'SET', key: 'startHour', value: startHour });
      dispatch({ type: 'SET', key: 'startMinute', value: startMinute });
      dispatch({ type: 'SET', key: 'endHour', value: endHour });
      dispatch({ type: 'SET', key: 'endMinute', value: endMinute });
      const nextDays = days.map(day => (day === 7 ? 0 : day));
      setSelectedDays(nextDays);
    }
  }, [scene, timer, work]);

  const toggleDay = debounce((index: number) => {
    const nextDays = selectedDays.includes(index)
      ? selectedDays.filter(i => i !== index)
      : [...new Set([...selectedDays, index])].sort((a, b) => a - b);
    setSelectedDays(nextDays);
    // 把0转换为7
    const nextDaysWith7 = nextDays.map(day => (day === 0 ? 7 : day));
    actions.work.set(
      Raw.generateWorkRaw(
        state.gear,
        state.startHour,
        state.startMinute,
        state.endHour,
        state.endMinute,
        nextDaysWith7
      )
    );
  }, 500);

  // 处理工作参数下发
  const handleWork = useMemo(() => {
    return debounce(
      (
        gear: number,
        startHour: number,
        startMinute: number,
        endHour: number,
        endMinute: number,
        days: number[]
      ) => {
        console.log('触发');
        const nextDaysWith7 = days.map(day => (day === 0 ? 7 : day));
        actions.work.set(
          Raw.generateWorkRaw(gear, startHour, startMinute, endHour, endMinute, nextDaysWith7)
        );
      },
      1000
    );
  }, []);

  const handleSceneClick = debounce((item, index, room, power) => {
    if (!power) return;
    if (room) {
      actions.scene.set(
        Raw.generateSceneRaw(item, sceneList[0], sceneList[1], sceneList[2], sceneList[3])
      );
      setSceneIndex(index);
      dispatch({ type: 'SET', key: 'scene', value: item });
    } else {
      router.push(`/custom?index=${index}`);
    }
  }, 500);

  // const gearConfig =
  //   state.scene <= 5 ? modeGearConfig.find(item => item.mode === state.scene)?.gear : defaultGear;

  return (
    <>
      <NavBar title={deviceInfo.name} customStyle={{ backgroundColor: 'transparent' }} border={false} />
      <View className={styles.view}>
        <View className={styles.header}>
          <Battery size={15} value={battery} type="horizontal" />
          <View className={styles.statusWarp}>
            <View
              className={clsx(styles.statusPanel, {
                [styles.statusPanelDisable]: !deviceInfo?.isOnline,
              })}
            >
              <View className={styles.statusBox}>
                {isWifiDevice ? (
                  <>
                    {deviceInfo?.isOnline ? (
                      <Icon name={require('@/res/icons/wifi.svg')} size={100} />
                    ) : (
                      <Icon name={require('@/res/icons/wifi_disabled.svg')} size={100} />
                    )}
                  </>
                ) : (
                  <>
                    {deviceInfo?.isOnline || deviceInfo?.isLocalOnline ? (
                      <Icon name={require('@/res/icons/ble.svg')} size={100} />
                    ) : (
                      <Icon name={require('@/res/icons/ble_disabled.svg')} size={100} />
                    )}
                  </>
                )}
              </View>
            </View>
          </View>

          <View>
            <View
              className={clsx(styles.powerOn, {
                [styles.powerOff]: !power,
              })}
              onClick={() => actions.switch.toggle()}
            >
              <Icon name={require('@/res/icons/power.svg')} color="red" size={18} />
            </View>
          </View>
        </View>
        <View className={styles.content}>
          <View
            className={clsx(styles.card, {
              [styles.disabled]: !power,
            })}
          >
            <View className={styles.modeHeader}>
              <View
                className={styles.flexBetween}
                onClick={() => {
                  if (!power) return;
                  setAromaNameField(aromaName);
                  setShowAromaNameDialog(true);
                }}
              >
                <Text>{Strings.getLang('scent')}</Text>
                <Icon name={Right} color="#BDBEBF" />
              </View>
              <View>
                <Text>{aromaName}</Text>
              </View>
            </View>
            <View className={styles.modeWarpper}>
              {sceneList.map((item, index) => {
                const room = SCENE_LLIST.find(room => room.key === item);
                const isActive = sceneIndex === index && state.scene === item;
                return (
                  <View
                    key={index}
                    className={clsx(styles.modeItem, {
                      [styles.modeItemActive]: isActive,
                    })}
                    onClick={() => handleSceneClick(item, index, room, power)}
                  >
                    {room ? (
                      <View
                        style={{
                          flex: 1,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'space-between',
                          position: 'relative',
                        }}
                      >
                        <Icon name={isActive ? room.checkIcon : room.icon} size={24} />
                        <Text className={styles.roomText}>{room.label}</Text>
                        {index >= 3 && (
                          <View
                            className={styles.poMoreBtn}
                            onClick={(e: any) => {
                              e.origin.stopPropagation();
                              router.push(`/custom?index=${index}`);
                            }}
                          >
                            <Icon name={Right} color="#fff" />
                          </View>
                        )}
                      </View>
                    ) : (
                      <View className={styles.customItem}>
                        <Text style={{ fontSize: 28, color: '#000' }}>
                          {Strings.getLang('custom_mode')}
                        </Text>
                        <View className={styles.customIcon}>
                          <Icon name={Right} color="#BDBEBF" />
                        </View>
                      </View>
                    )}
                  </View>
                );
              })}
            </View>
          </View>

          <View
            className={clsx(styles.card, {
              [styles.disabled]: !power,
            })}
            style={{ gap: 10 }}
          >
            <View className={styles.cell}>
              <View>
                <Text>{Strings.getLang('timer')}</Text>
              </View>
              <View
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '0 50rpx',
                }}
              >
                <Picker
                  mode="selector"
                  onChange={(e: any) => {
                    const newHour = +e.value;
                    actions.timer.set(Raw.generateTimingRaw(state.timerSwitch, newHour + 1));
                    dispatch({ type: 'SET', key: 'timerHour', value: newHour });
                  }}
                  range={Array.from(
                    { length: 24 },
                    (_, i) => `${i + 1}${Strings.getLang('hours')}`
                  )}
                  value={state.timerHour}
                >
                  <View className={styles.flexBetween}>
                    <Text style={{ flexDirection: 'row' }}>
                      {state.timerHour + 1} {Strings.getLang('hours')}
                    </Text>
                    <Icon name={Right} color="#BDBEBF" />
                  </View>
                </Picker>
                <View
                  style={{
                    flex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'flex-end',
                    marginLeft: 10,
                  }}
                >
                  {state.timerSwitch && timerCountDown > 0 && (
                    <Text>
                      {Strings.getLang('toast3')}
                      {timerCountDown}
                      {Strings.getLang('minutes')}
                    </Text>
                  )}
                </View>
              </View>
              <View>
                <SmartSwitch
                  value={state.timerSwitch}
                  onChange={(value: boolean) => {
                    dispatch({ type: 'SET', key: 'timerSwitch', value });
                    actions.timer.set(Raw.generateTimingRaw(value, state.timerHour + 1));
                  }}
                />
              </View>
            </View>
            <View className={styles.divider} />
            <View className={styles.cell}>
              <View>
                <Text>{Strings.getLang('section')}</Text>
              </View>
              <View className={styles.levelWrap}>
                <Picker
                  mode="time"
                  value={`${state.startHour.toString().padStart(2, '0')}:${state.startMinute
                    .toString()
                    .padStart(2, '0')}`}
                  onChange={(e: any) => {
                    const { value } = e.detail;
                    const [hourStr, minuteStr] = value.split(':'); // value 是 "02:00"
                    handleWork(
                      state.gear,
                      Number(hourStr),
                      Number(minuteStr),
                      state.endHour,
                      state.endMinute,
                      selectedDays
                    );
                    dispatch({
                      type: 'SET',
                      key: 'startHour',
                      value: Number(hourStr),
                    });
                    dispatch({
                      type: 'SET',
                      key: 'startMinute',
                      value: Number(minuteStr),
                    });
                  }}
                >
                  <View style={{ flexDirection: 'row', gap: 10 }}>
                    <Text>
                      {`${state.startHour.toString().padStart(2, '0')}:${state.startMinute
                        .toString()
                        .padStart(2, '0')}`}
                    </Text>
                    <Text style={{ color: '#C0C0C0' }}> {Strings.getLang('start')}</Text>
                  </View>
                </Picker>
                <View className={styles.dividerVertical} />
                <Picker
                  mode="time"
                  value={`${state.endHour.toString().padStart(2, '0')}:${state.endMinute
                    .toString()
                    .padStart(2, '0')}`}
                  onChange={(e: any) => {
                    const { value } = e.detail;
                    const [hourStr, minuteStr] = value.split(':'); // value 是 "02:00"
                    handleWork(
                      state.gear,
                      state.startHour,
                      state.startMinute,
                      Number(hourStr),
                      Number(minuteStr),
                      selectedDays
                    );
                    dispatch({
                      type: 'SET',
                      key: 'endHour',
                      value: Number(hourStr),
                    });
                    dispatch({
                      type: 'SET',
                      key: 'endMinute',
                      value: Number(minuteStr),
                    });
                  }}
                >
                  <View style={{ flexDirection: 'row', gap: 10 }}>
                    <Text>
                      {`${state.endHour.toString().padStart(2, '0')}:${state.endMinute
                        .toString()
                        .padStart(2, '0')}`}
                    </Text>
                    <Text style={{ color: '#C0C0C0' }}> {Strings.getLang('end')}</Text>
                  </View>
                </Picker>
              </View>
            </View>
            <View className={styles.divider} />
            <View className={styles.cell}>
              <View>
                <Text>{Strings.getLang('gear')}</Text>
              </View>
              <View className={styles.levelWrap}>
                <View
                  onClick={() => {
                    if (state.gear > 1) {
                      const newGear = state.gear - 1;
                      handleWork(
                        newGear,
                        state.startHour,
                        state.startMinute,
                        state.endHour,
                        state.endMinute,
                        selectedDays
                      );
                      dispatch({ type: 'SET', key: 'gear', value: newGear });
                    }
                  }}
                >
                  <Icon
                    name={MinusCircle}
                    size={35}
                    color={state.gear !== 1 ? '#5195D0' : '#ccc'}
                  />
                </View>
                <View className={styles.gearText} style={{ flexDirection: 'row', gap: 12 }}>
                  <Text>
                    {Strings.getLang('operate')}
                    {Number(state.gear || 0) * 10}S
                  </Text>
                  <Text>~</Text>
                  <Text>
                    {Strings.getLang('pause')}
                    120S
                  </Text>
                </View>
                <View
                  onClick={() => {
                    if (state.gear < 9) {
                      const newGear = state.gear + 1;
                      handleWork(
                        newGear,
                        state.startHour,
                        state.startMinute,
                        state.endHour,
                        state.endMinute,
                        selectedDays
                      );
                      dispatch({ type: 'SET', key: 'gear', value: newGear });
                    }
                  }}
                >
                  <Icon name={PlusCircle} size={35} color={state.gear !== 9 ? '#5195D0' : '#ccc'} />
                </View>
              </View>
            </View>
            <View className={styles.divider} />
            <View className={styles.cell}>
              <View>
                <Text>{Strings.getLang('cycle')}</Text>
              </View>
              <View className={styles.cycleWrap}>
                {days.map((day, index) => {
                  const isSelected = selectedDays.includes(index);
                  return (
                    <View
                      key={index}
                      className={isSelected ? styles.selectedDay : styles.day}
                      onClick={() => toggleDay(index)}
                    >
                      <Text>{day}</Text>
                    </View>
                  );
                })}
              </View>
            </View>
          </View>
        </View>
        <Dialog
          useSlot
          title={Strings.getLang('scent')}
          show={showAromaNameDialog}
          showCancelButton
          confirmButtonText={Strings.getLang('confirm')}
          cancelButtonText={Strings.getLang('cancel')}
          onClose={() => setShowAromaNameDialog(false)}
          onConfirm={handleAromaNameConfirm}
        >
          <View style={{ marginBottom: 20 }}>
            <Field
              value={aromaNameField}
              placeholder={Strings.getLang('scent_description')}
              maxlength={6}
              border
              clearable
              inputAlign="left"
              onChange={(e: any) => setAromaNameField(e.detail)}
            />
          </View>
        </Dialog>
      </View>
    </>
  );
}
